/**
 * 科室选择框
 * 对于非供应室来说 是物品选择 而供应室 则是包选择
 * @author banglong
 * @date 2016/8/19.
 */
define(['Layer', 'text!../html/components/common/goodsSelectTemp.html!strip', 'layPage', 'rootPath', 'avalon',
    'tools', 'Condition', 'Conditions', 'newBillApi', 'conditionsUtils',
    'text!../html/index/bill/ViewImgOperate.html!strip'
  ],
  function (layer, htmlTemp, laypage, rootPath, avalon, tools, Condition, Conditions,
    api, conditionsUtils, viewImgOperate) {

    // 设定路径
    laypage.dir = rootPath.getRootPath() + 'js/common/laypage/skin/laypage.css';
    return function () {

      var runtimeParam;
      var getRuntimeParam = function () {
        return {
          layeroObj: -1,
          timeFlag: {}
        };
      };

      var goodsSelectVm;
      var getVmOption = function () {
        return {
          $id: 'goodsSelectDialog',
          searchInput: '',
          goods: [],
          isGYKS: false,
          BillType: '',

          size: 20, // 大小
          pages: 0, // 页数
          count: 0, // 总数
          currentPages: 0, // 当前页码
          active: 'active', // 单击效果
          chooseGoodsIndex: 0, // 单击选择的index

          header: [],
          row: [],
          tableComponentsID: ['goodsSelectTable'],

          freshIconId: 'freshId',
          showFreshIcon: true,
          isProviderDept: false,
          type: '0',

          disabledNoValidate: true, // 禁止 不流通
          goodsName: '物品名称',
          goodsCount: 0,
          goodsMaxBatch: '时间', // 最新进货时间

          viewImgOperate: viewImgOperate,
          operateCustomEvent: {},

          handleClick: function (index) { // 单击事件
            goodsSelectVm.chooseGoodsIndex = index;
          },

          handleDBClick: function (index) {
            if (goodsSelectVm.goods.length > 0) {
              var goods = JSON.parse(JSON.stringify(goodsSelectVm.goods[index].$model));
              chooseGoods(goods);
            }
          },

          sureGoods: function () { // 确定事件
            if (goodsSelectVm.goods.length > 0) {
              var goods = JSON.parse(JSON.stringify(goodsSelectVm.goods[goodsSelectVm.chooseGoodsIndex].$model));
              chooseGoods(goods);
            }
          },

          hideDialog: function () {
            layer.close(runtimeParam.layeroObj);
          },

          handleSubmit: function (e) {
            e.preventDefault();
            if (goodsSelectVm.goods.length > 0) {
              var goods = JSON.parse(JSON.stringify(goodsSelectVm.goods[goodsSelectVm.chooseGoodsIndex].$model));
              chooseGoods(goods);
            }
          },

          handleInputSearch: function () { // 搜索
            handleSearch();
          },

          handleKeydown: function (e) {
            var theEvent = e || window.event;
            var code = theEvent.keyCode || theEvent.which || theEvent.charCode;
            switch (code) {
              case 13:
                return;
                break;
            }
          },
          chooseDataFun: function (goods) {
            chooseGoods(goods);
          },
          showImg: function(event, index) {
            tools.throttle(runtimeParam.timeFlag, function () {
              var goods = goodsSelectVm.goods[index];
              // 需要查询物品的地址信息 todo
              api.getImages({
                  className: 'ImageManager',
                  method: 'getImages',
                  imgType: '6',
                  goodsType: 1,
                  folder: goods.GoodsCode
                })
                .then(function (data) {
                  if (data.issuccess === 0) {
                    var result = JSON.parse(data.result);
                    if (result.length > 0) {
                      //tools.showImg(event, result[0], runtimeParam)();
                      tools.showImgDialog(result)();
                    }
                  }
                })
            });
          }
        }
      };

      // 选择 商品
      function chooseGoods(goods) {
        if (goodsSelectVm.isGYKS) { // 供应室 有些参数不同
          goods.GoodsID = goods.PackageID;
          goods.GoodsCode = goods.PackageCode;
          goods.GoodsName = goods.PackageName;
          goods.LatestPrice = goods.Price;
        }
        goods.GoodsCount = goodsSelectVm.goodsCount; // 库存
        goods.ApplyNum = 0; // 申请数量
        goods.consultMoney = 0; // 参考价格
        goods.RefPrice = goods.LatestPrice; // 实际价格
        goods.Comment = ''; // 通用备注
        goods.bz = ''; // 申请单备注
        goods.Unit = goods.SplitUnit; // 申请单规格
        goods.Price = goods.LatestPrice; // 申请单价格
        runtimeParam.pushChooseGoods(goods);
        layer.close(runtimeParam.layeroObj);
      }

      function handleSearch() {
        tools.throttle(runtimeParam.timeFlag, function () {
          // 搜索的时候将 当前页数清零
          runtimeParam.nowPage = 1;
          getGoodsToDataSet(api, runtimeParam);
        });
      }

      function getGoodCount(Goods) {
    	  //console.log(goodsSelectVm)
        // 加载所有物品的时候不需要 查询数量
        if (runtimeParam.getAll) return;
        if(runtimeParam.OutDeptAccountID==="0000000000z-18"&&runtimeParam.BillType==='ly'){
        	 
       	  var param = {
        		className: 'LHDockingManager',
 	            method: 'GetGoodsStockInfo',
 	            goodsCode: Goods.GoodsCode,
        	 }
       	 api.getGoodsBatchStatus(param).then(function (jsonResult) {
       		  
       		  if (jsonResult.issuccess !== 0) {
	              return Promise.reject('获取信息失败');
	            }
       		var result = JSON.parse(jsonResult.result);
       	   
       		 if(!result||!result.GoodsStock){
       			//goodsSelectVm.goodsName = '';
    	       	//goodsSelectVm.goodsCount = 0;
    	       // goodsSelectVm.goodsMaxBatch = "";
    	        var getCountClassName = 'StoreBatchManager',
                getCountMethod = 'GetGoodsBatchStatus';
  	          if (goodsSelectVm.isGYKS) {
  	            getCountClassName = 'PackageStoreManager';
  	            getCountMethod = 'GetFormalCurrentCount';
  	          }
  	          var param = {
  	            className: getCountClassName,
  	            method: getCountMethod,
  	            goodsID: Goods.GoodsID,
  	            deptAccountID: runtimeParam.OutDeptAccountID
  	          };
  	          param = !goodsSelectVm.isGYKS ? param : Object.assign({}, param, {
  	            packageID: Goods.PackageID
  	          });
  	
  	          api.getGoodsBatchStatus(param).then(function (jsonResult) {
  	          	
  	            if (jsonResult.issuccess !== 0) {
  	              return Promise.reject('获取信息失败');
  	            }
  	            var res = JSON.parse(jsonResult.result);
  	           
  	            
  	            goodsSelectVm.goodsName = (Goods.GoodsName) || Goods.PackageName;
  	
  	            if (!goodsSelectVm.isGYKS) {
  	              goodsSelectVm.goodsCount = res.GoodsCount;
  	               
  	              goodsSelectVm.goodsMaxBatch = res.LatestReceiveTime;
  	            } else {
  	              goodsSelectVm.goodsCount = res;
  	             
  	            
  	              param = Object.assign({}, param, {
  	                className: 'PackageStoreManager',
  	                method: 'GetDirtyCurrentCount'
  	              });
  	              api.getGoodsBatchStatus(param).then(function (jsonResult) {
  	                if (jsonResult.issuccess !== 0) {
  	                  return Promise.reject('获取信息失败');
  	                }
  	                goodsSelectVm.goodsMaxBatch = jsonResult.result;
  	              });
  	            }
  	
  	          })['catch'](function (ex) {
  	            // tools.handleError(ex);
  	          });
       		 }else{
       			goodsSelectVm.goodsName = result.GoodsName ? result.GoodsName : '';
    	       	goodsSelectVm.goodsCount = result.GoodsStock ? result.GoodsStock : 0;
    	        goodsSelectVm.goodsMaxBatch = "";
       		 }
       		
       		
       	 })
        }else{
        	  var getCountClassName = 'StoreBatchManager',
              getCountMethod = 'GetGoodsBatchStatus';
	          if (goodsSelectVm.isGYKS) {
	            getCountClassName = 'PackageStoreManager';
	            getCountMethod = 'GetFormalCurrentCount';
	          }
	          var param = {
	            className: getCountClassName,
	            method: getCountMethod,
	            goodsID: Goods.GoodsID,
	            deptAccountID: runtimeParam.OutDeptAccountID
	          };
	          param = !goodsSelectVm.isGYKS ? param : Object.assign({}, param, {
	            packageID: Goods.PackageID
	          });
	
	          api.getGoodsBatchStatus(param).then(function (jsonResult) {
	          	
	            if (jsonResult.issuccess !== 0) {
	              return Promise.reject('获取信息失败');
	            }
	            var result = JSON.parse(jsonResult.result);
	            goodsSelectVm.goodsName = (Goods.GoodsName) || Goods.PackageName;
	
	            if (!goodsSelectVm.isGYKS) {
	              goodsSelectVm.goodsCount = result.GoodsCount;
	              goodsSelectVm.goodsMaxBatch = result.LatestReceiveTime;
	            } else {
	              goodsSelectVm.goodsCount = result;
	              param = Object.assign({}, param, {
	                className: 'PackageStoreManager',
	                method: 'GetDirtyCurrentCount'
	              });
	              api.getGoodsBatchStatus(param).then(function (jsonResult) {
	                if (jsonResult.issuccess !== 0) {
	                  return Promise.reject('获取信息失败');
	                }
	                goodsSelectVm.goodsMaxBatch = jsonResult.result;
	              });
	            }
	
	          })['catch'](function (ex) {
	            // tools.handleError(ex);
	          });
        }
        
      }

      // 隐藏刷新标志
      var hideRefreshIcon = function () {
        layer.close(runtimeParam.loadingIndex); // 隐藏刷新圈
        goodsSelectVm.showFreshIcon = false;
      };

      // 构建分页组件
      var initPage = function (goodsSelectVm, goods) {
        var page = document.querySelector('#goodpage');
        page.html = '';
        laypage({
          cont: page,
          curr: goodsSelectVm.currentPages,
          pages: goodsSelectVm.pages,
          jump: function (obj, first) {

            goodsSelectVm.goods.splice(0, goodsSelectVm.goods.length);
            goodsSelectVm.chooseGoodsIndex = 0;
            goodsSelectVm.goods.pushArray(goods);

            if (!first) {
              //得到了当前页，用于向服务端请求对应数据
              runtimeParam.nowPage = obj.curr;
              getGoodsToDataSet(api, runtimeParam);
            }
          }
        });

        hideRefreshIcon();
        $('.layui-layer-content').css('overflow', 'hidden'); //修改样式 避免样式变形
      };

      function initGoodsArray(jsonResult, param) {
        var result = JSON.parse(jsonResult.result);
        var goods = result.pageContent.concat();

        goods.forEach(function (data) {
          if (goodsSelectVm.isGYKS) {
            data.GoodsID = data.PackageCode;
          } else {
            if (!data.IsImmediatelyUse) {
              data.class = 'D1FCFC';
            }
            if (!data.IsOpen) {
              data.class = 'FFACAC';
            }
          }
          // 计算税前加个
          if (typeof data.TaxRate === 'number') {
            if (data.TaxRate === 0) {
              data.PreTaxPrice = data.LatestPrice
            } else {
              data.PreTaxPrice = (parseFloat(data.LatestPrice) / (1 + data.TaxRate)).toFixed(3)
            }
          }

          if (!!data.PicturePath && data.PicturePath !== '-999') {
            data.hasPic = '有'
          } else {
            data.hasPic = '无'
          }
        });

        goodsSelectVm.pages = Math.ceil(result.pageCount / result.pageSize);
        goodsSelectVm.count = result.pageCount;
        goodsSelectVm.currentPages = result.nowPage;
        result = null;

        // 设置分页
        initPage(goodsSelectVm, goods);
        // 刷新第一个库存信息
        if (goodsSelectVm.goods.length > 0) {
          var good = goodsSelectVm.goods[0];
          getGoodCount(good);
        }
      }

      // 获取所有的物品
      function getGoodsToDataSet(api, param) {

        runtimeParam.loadingIndex = layer.load(); // 加载
        goodsSelectVm.showFreshIcon = true; //  是否正在加载数据
        goodsSelectVm.currentPages = runtimeParam.nowPage || 1;
        var className = 'GoodsManager',
          method = 'GetGoodsToDataSetForWeb'; // 设置请求地址 //GetGoodsToDataSetForWeb
        if(goodsSelectVm.BillType=="sq"){
    	   className = 'GoodsManager',
           method = 'GetGoodsToDataSetForWebSqd';
       }
        if (goodsSelectVm.isGYKS) {
          className = 'SysPackageManager';
          method = 'GetPackageForWeb';
        }
        
        var condition;
        if (goodsSelectVm.isGYKS) { // 正常的供应科室 领用单 调用
          var PackageBigCat = runtimeParam.getAll ? '' : runtimeParam.Openparm.PackageBigCat;
          condition = JSON.stringify(conditionsUtils.getPackageCondition({
            searchValue: goodsSelectVm.searchInput,
            PackageBigCat: PackageBigCat // 包大类
          }));
        } else { // 基本的单据 调用方式
          var isProviderDept = false;
          if (runtimeParam.getAll || runtimeParam.isProviderDept) {
            isProviderDept = true;
          }
          // 申请单 需要特殊处理
          condition = JSON.stringify(conditionsUtils.getGoodsCondition({
            IsOpen: goodsSelectVm.type === '0',
            IsImmediatelyUse: !runtimeParam.isProviderDept,
            GoodsBookID: runtimeParam.Openparm.GoodsBook || runtimeParam.GoodsBookID,
            searchValue: goodsSelectVm.searchInput,
            isProviderDept: isProviderDept,
            BillType: runtimeParam.BillType
          }));
        }

        api.getGoodsToDataSet({
          className: className,
          method: method,
          condition: condition,
          nowPage: runtimeParam.nowPage || 1,
          pageSize: goodsSelectVm.size || 10
        }).then(function (jsonResult) {
        	
          if (jsonResult.issuccess !== 0) {
            return Promise.reject("系统错误，请联系管理员！");
          }
          initGoodsArray(jsonResult, param);
          focusOnSearchInput();

        })['catch'](function (ex) {
          hideRefreshIcon();
          tools.handleError(ex);
        });
      }

      function focusOnSearchInput() {
        setTimeout(function () {
          document.querySelector('#searchInputForGoods').focus();
        }, 50);
      }

      this.init = function (param) {
        runtimeParam = getRuntimeParam();
        runtimeParam = Object.assign(runtimeParam, param);
        runtimeParam.getGoodsCondition = param.condition; // 加载物品信息的条件
        runtimeParam.refresh = true;

        var VmConfig = getVmOption();
        VmConfig = Object.assign({}, VmConfig, {
          operateCustomEvent: {
            handleView: VmConfig.showImg,
          }
        })

        runtimeParam.layeroObj = tools.createNewOpenWindow(['850px', '620px'], '物品查询', htmlTemp, null, {
          vmConfig: VmConfig,
          // 销毁方法
          destroy: function () {
            runtimeParam = null;
            goodsSelectVm = null;
          }
        });

        if (param.isGYKS) {
          VmConfig.header = ['包代码', '包名称', '型号规格', '拼音码', '包价格'];
          VmConfig.row = ['PackageCode', 'PackageName', 'GoodsSpec', 'PyCode', 'Price'];
        } else {
          VmConfig.header = ['物品代码', '物品名称', '规格型号', '计量单位', '最新税后单价', '最新税前单价', '供货单位'];
          VmConfig.row = ['GoodsCode', 'GoodsName', 'GoodsSpec', 'SplitUnit', 'LatestPrice', 'PreTaxPrice', 'SupplierName'];
        }
        goodsSelectVm = tools.initAvalonVm(avalon, VmConfig, ".goodsSelectDialogContent");
        goodsSelectVm.$watch('chooseGoodsIndex', function (index) {
          var Goods = goodsSelectVm.goods[index];
          getGoodCount(Goods);
        });

        goodsSelectVm.$watch('type', function () { // type 的改变 (流通 or 不流通)
          // 当刷新圈还在的时候不能 调用 为了防止产生异常 产生错误的分页结果
          if (!goodsSelectVm.showFreshIcon) {
            handleSearch();
          }
        });

        // 是否是供应室
        goodsSelectVm.isGYKS = param.isGYKS;
        goodsSelectVm.BillType = param.BillType;
        // 判断当前科室 是否是 供应科室 getALl 拥有和供应科室一样的权限
        runtimeParam.isProviderDept = runtimeParam.getAll ? runtimeParam.getAll : (runtimeParam.ProviderDeptAccount.DeptAccountID === runtimeParam.CurrentDeptAccount.DeptAccountID);
        goodsSelectVm.isProviderDept = runtimeParam.isProviderDept;
        goodsSelectVm.searchInput = runtimeParam.searchValue; // 查询条件

        // 可以流通 当前科室不是 供应科室的时候 只能 点击流通 不能选择非流通的 数据
        if (runtimeParam.isProviderDept) {
          goodsSelectVm.disabledNoValidate = false;
        }

        getGoodsToDataSet(api, param); // 查询数据
      };
    };
  });